package com.xuyuan.concurrent.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolWithThreadLocalDemo {
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 提交任务到线程池
        for (int i = 0; i < 5; i++) {
            executorService.submit(new MyRunnable(i));
        }

        // 关闭线程池
        executorService.shutdown();
    }

    static class MyRunnable implements Runnable {
        private int taskId;

        public MyRunnable(int taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            // 设置任务ID到ThreadLocal变量中
            threadLocal.set(taskId);

            // 模拟业务逻辑的处理过程
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 获取任务ID从ThreadLocal变量中
            System.out.println("Task ID in thread " + Thread.currentThread().getName() + ": " + threadLocal.get());

            // 清除ThreadLocal变量
            threadLocal.remove();
        }
    }
}